﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;

namespace IronSharePoint.Web.WebControls
{
    public class IronWebPartEditor : EditorPart
    {
        protected SimpleTextEditor steScriptEditor;
        protected IronWebPart ironWebPart;
        protected DropDownList ddlScriptingLanguage;

        protected override void CreateChildControls()
        {
            ironWebPart = (IronWebPart)this.WebPartToEdit;

            ddlScriptingLanguage = new DropDownList();
            ddlScriptingLanguage.DataSource = Enum.GetNames(typeof(IronScriptingLanguage));
            ddlScriptingLanguage.DataBind();
            this.Controls.Add(ddlScriptingLanguage);

            WebControl wbBr = new WebControl(System.Web.UI.HtmlTextWriterTag.Br);
            this.Controls.Add(wbBr);

            steScriptEditor = new SimpleTextEditor();
            steScriptEditor.Title = "Iron Script Editor";
            steScriptEditor.ButtonText = "Edit Script";
            this.Controls.Add(steScriptEditor);

            base.CreateChildControls();
        }

        public override bool ApplyChanges()
        {
            EnsureChildControls();

            ironWebPart.Script = steScriptEditor.Text;
            ironWebPart.ScriptSigning = IronScriptSigner.SignScript(ironWebPart.Script);
            ironWebPart.ScriptLanguage = (IronScriptingLanguage)Enum.Parse(typeof(IronScriptingLanguage), ddlScriptingLanguage.SelectedValue);

            return true;
        }

        public override void SyncChanges()
        {
            EnsureChildControls();

            steScriptEditor.Text = ironWebPart.Script;
            ddlScriptingLanguage.SelectedValue = ironWebPart.ScriptLanguage.ToString() ;
        }
    }
}
